<template>
  <div class="llm-settings">
    <div class="settings-container">
      <button class="provider-settings" title="添加模型供应商" @click="openProviderDialog()">
        <img src="@/assets/icon/provider-config.png" alt="provider settings" class="settings-icon" />
      </button>
    </div>

    <div class="model-cards">
      <div v-for="provider in providers" :key="provider.name" class="model-card">
        <div class="card-header">
          <img :src="provider.avatar || llmIcon" :alt="provider.name" class="provider-logo">
          <div class="provider-info">
            <h2>{{ provider.name }}</h2>
            <p class="provider-description">{{ provider.description  }}</p>
          </div>
          <div class="provider-actions">
            <button class="edit-provider" @click="editProvider(provider)" title="配置供应商">
              <img src="@/assets/icon/setting.png" alt="settings" class="setting-icon" />
            </button>
            <button class="delete-provider" @click="deleteProvider(provider)" title="删除供应商">
              <img src="@/assets/icon/delete.png" alt="delete" class="setting-icon" />
            </button>
          </div>
        </div>
        <div class="capabilities">
          <span v-for="(value, key) in provider.labels" 
                :key="key" 
                class="tag">
            {{ key }}={{ value }}
          </span>
        </div>

        <!-- Models section -->
        <div class="models-section">
          <div class="models-header">
            <div class="model-count-section" @click="toggleModels(provider)">
              <img 
                :src="getProviderExpandedIcon(provider.name)" 
                :alt="isProviderExpanded(provider.name) ? 'collapse' : 'expand'"
                class="expand-icon"
              />
              <span class="model-count">{{ getModelCount(provider) }} Models</span>
            </div>
          </div>
          
          <!-- Models list (shown when expanded) -->
          <div v-if="isProviderExpanded(provider.name)" class="models-list">
            <div v-for="model in getModels(provider)" :key="model.urn" class="model-item">
              {{ model.name }} ({{ model.model }})
              <div class="model-actions">
                <el-dropdown trigger="click">
                  <button class="more-actions">
                    <img src="@/assets/icon/more-vertical.png" alt="more" class="more-icon" />
                  </button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item @click="editModel(model)" title="编辑">
                        <img src="@/assets/icon/edit.png" alt="edit" class="menu-icon" /> 编辑
                      </el-dropdown-item>
                      <el-dropdown-item @click="deleteModel(model)" title="删除">
                        <img src="@/assets/icon/delete.png" alt="delete" class="menu-icon" /> 删除
                      </el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
            <!-- <button class="add-model" @click="addModel(provider)" title="增加模型">
              <img src="@/assets/icon/more-icon.png" alt="add" class="add-icon" />
            </button> -->
          </div>
            <button class="add-model" @click="addModel(provider)" title="增加模型">
              <img src="@/assets/icon/more-icon.png" alt="add" class="add-icon" />
            </button>
        </div>
      </div>
    </div>

    <!-- Provider Create/Edit Dialog -->
    <el-dialog
      v-model="providerDialogVisible"
      :title="currentProvider ? '编辑模型供应商' : '添加模型供应商'"
      width="50%"
    >
      <el-form :model="providerForm" label-width="120px">
        <!-- Provider Selection -->
        <el-form-item label="供应商类型">
          <el-select 
            v-model="providerForm.specName" 
            placeholder="请选择供应商"
            @change="handleProviderSpecChange"
          >
            <el-option
              v-for="[name, spec] in Array.from(providerSpecs.entries())"
              :key="name"
              :label="name"
              :value="name"
            />
          </el-select>
        </el-form-item>

        <!-- Basic Configuration -->
        <template v-if="selectedSpec">
          <!-- Provider Configuration -->
          <template v-if="selectedSpec.providerConfig && selectedSpec.providerConfig.length > 0">
            <el-form-item
              v-for="config in selectedSpec.providerConfig.filter(c => c.appear)"
              :key="config.variable"
              :label="config.showName"
              :required="config.required"
            >
              <template v-if="config.options && config.options.length > 0">
                <el-select
                  v-model="providerForm.config[config.variable]"
                  :placeholder="config.defaultValue"
                  :disabled="config.immutable"
                >
                  <el-option
                    v-for="option in config.options"
                    :key="option"
                    :label="option"
                    :value="option"
                  />
                </el-select>
              </template>
              <template v-else>
                <el-input
                  :model-value="providerForm.config[config.variable] || config.defaultValue"
                  @update:model-value="val => providerForm.config[config.variable] = val"
                  :type="config.type === 'password' ? 'password' : 'text'"
                  :placeholder="config.description"
                  :disabled="config.immutable"
                  :show-password="config.type === 'password'"
                />
              </template>
            </el-form-item>
          </template>

          <!-- Auth Configuration -->
          <template v-if="selectedSpec.authConfig && selectedSpec.authConfig.length > 0">
            <el-form-item
              v-for="config in selectedSpec.authConfig.filter(c => c.appear)"
              :key="config.variable"
              :label="config.showName"
              :required="config.required"
            >
              <template v-if="config.options && config.options.length > 0">
                <el-select
                  v-model="providerForm.authInfo[config.variable]"
                  :placeholder="config.defaultValue"
                  :disabled="config.immutable"
                >
                  <el-option
                    v-for="option in config.options"
                    :key="option"
                    :label="option"
                    :value="option"
                  />
                </el-select>
              </template>
              <template v-else>
                <el-input
                  :model-value="providerForm.authInfo[config.variable] || config.defaultValue"
                  @update:model-value="val => providerForm.authInfo[config.variable] = val"
                  :type="config.type === 'password' ? 'password' : 'text'"
                  :placeholder="config.description"
                  :disabled="config.immutable"
                  :show-password="config.type === 'password'"
                />
              </template>
            </el-form-item>
          </template>
        </template>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="providerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProvider">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加供应商编辑对话框 -->
    <el-dialog
      v-model="providerEditDialogVisible"
      title="编辑模型供应商"
      width="50%"
    >
      <el-form :model="providerEditForm" label-width="120px">
        <template v-if="currentProvider && selectedEditSpec">
          <!-- Provider Configuration -->
          <template v-if="selectedEditSpec.providerConfig && selectedEditSpec.providerConfig.length > 0">
            <el-form-item
              v-for="config in selectedEditSpec.providerConfig.filter(c => c.appear)"
              :key="config.variable"
              :label="config.showName"
              :required="config.required"
            >
              <template v-if="config.options && config.options.length > 0">
                <el-select
                  v-model="providerEditForm.config[config.variable]"
                  :placeholder="config.defaultValue"
                  :disabled="config.immutable"
                >
                  <el-option
                    v-for="option in config.options"
                    :key="option"
                    :label="option"
                    :value="option"
                  />
                </el-select>
              </template>
              <template v-else>
                <el-input
                  v-model="providerEditForm.config[config.variable]"
                  :type="config.type === 'password' ? 'password' : 'text'"
                  :placeholder="config.description"
                  :disabled="config.immutable"
                  :show-password="config.type === 'password'"
                />
              </template>
            </el-form-item>
          </template>

          <!-- Auth Configuration -->
          <template v-if="selectedEditSpec.authConfig && selectedEditSpec.authConfig.length > 0">
            <el-form-item
              v-for="config in selectedEditSpec.authConfig.filter(c => c.appear)"
              :key="config.variable"
              :label="config.showName"
              :required="config.required"
            >
              <template v-if="config.options && config.options.length > 0">
                <el-select
                  v-model="providerEditForm.authInfo[config.variable]"
                  :placeholder="config.defaultValue"
                  :disabled="config.immutable"
                >
                  <el-option
                    v-for="option in config.options"
                    :key="option"
                    :label="option"
                    :value="option"
                  />
                </el-select>
              </template>
              <template v-else>
                <el-input
                  v-model="providerEditForm.authInfo[config.variable]"
                  :type="config.type === 'password' ? 'password' : 'text'"
                  :placeholder="config.description"
                  :disabled="config.immutable"
                  :show-password="config.type === 'password'"
                />
              </template>
            </el-form-item>
          </template>
        </template>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="providerEditDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveProviderSettings">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- Model Create Dialog -->
    <el-dialog
      v-model="modelDialogVisible"
      title="添加模型"
      width="50%"
    >
      <el-form :model="modelForm" label-width="120px">
        <el-form-item label="模型名称" required>
          <el-input
            v-model="modelForm.model"
            placeholder="请输入模型名称"
          />
        </el-form-item>
        <el-form-item label="模型类型" required>
          <el-select 
            v-model="modelForm.modelType" 
            placeholder="请选择模型类型"
          >
            <el-option label="Chat" value="CHAT" />
            <el-option label="Embedding" value="EMBEDDING" />
          </el-select>
        </el-form-item>
        
        <!-- 添加 Embedding Length 配置项，仅在类型为 EMBEDDING 时显示 -->
        <el-form-item 
          v-if="modelForm.modelType === 'EMBEDDING'" 
          label="嵌入向量长度" 
          required
        >
          <el-input
            v-model="modelForm.embeddinglen"
            placeholder="请输入embedding向量长度"
            type="number"
          />
        </el-form-item>
        <el-form-item 
          v-if="modelForm.modelType === 'CHAT'" 
          label="token上限" 
          required
        >
          <el-input
            v-model="modelForm.tokenslen"
            placeholder="请输入embedding向量长度"
            type="number"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="modelDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveModel">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { CreateLLMProviderRequest, LLMProvider, LLMProviderSpec,ListLLMProviderRequest, ListLLMProviderResponse, DeleteLLMProviderRequest, UpdateLLMProviderRequest} from "@/types/proto/api/v1/llm_service";
import { CreateLLMModelRequest, LLMModel, ModelType, ListLLMModelRequest, ListLLMModelResponse, DeleteLLMModelRequest, UpdateLLMModelRequest} from "@/types/proto/api/v1/llm_service";
import { ListLLMProviderSpecRequest, ListLLMProviderSpecResponse, ModelSpecUnit, SpecUnit} from "@/types/proto/api/v1/llm_service";

import {ListProviders, ListModels, ListProviderSpec, CreateProvider, CreateModel, UpdateProvider, DeleteModel,DeleteProvider, UpdateModel} from '@/api/llm'
import { ElInput, ElDialog, ElMessage } from 'element-plus'
import { ref, onMounted, nextTick, computed, watch } from 'vue'
import expandIconLess from "@/assets/icon/expand-less.png"
import expandIconMore from "@/assets/icon/expand-more.png"
import llmIcon from '@/assets/icon/llm.png'

const providers = ref<LLMProvider[]>([])
const providerModels = ref(new Map<string, LLMModel[]>())
const providerSpecs = ref(new Map<string, LLMProviderSpec>())
const expandedProviders = ref(new Map<string, boolean>())
const pageSize = 10
const totalProvider = ref(0)

const toggleModels = (provider: LLMProvider) => {
  const isExpanded = expandedProviders.value.get(provider.name) || false
  expandedProviders.value.set(provider.name, !isExpanded)
}

const isProviderExpanded = (providerName: string): boolean => {
  return expandedProviders.value.get(providerName) || false
}

const getProviderExpandedIcon = (providerName: string): string => {
  let expand = expandedProviders.value.get(providerName) || false
  let icon = expand?expandIconLess:expandIconMore
  return icon
}

const dialogVisible = ref(false)
const currentProvider = ref<LLMProvider>()
const currentAuthKey = ref('')
const authValue = ref('')

const openAuthSettings = (provider: LLMProvider, key: string) => {
  currentProvider.value = provider
  currentAuthKey.value = key
  authValue.value = provider.authInfo[key] || ''
  dialogVisible.value = true
}

const saveAuthSettings = () => {
  if (!authValue.value.trim()) {
    ElMessage.warning('Please enter a valid value')
    return
  }

  if (currentProvider.value && currentAuthKey.value) {
    currentProvider.value.authInfo[currentAuthKey.value] = authValue.value
    // 这里可以添加保存到后端的逻辑
  }
  
  dialogVisible.value = false
  ElMessage.success('Settings saved successfully')
}

const addModel = (provider: LLMProvider) => {
  modelForm.value = {
    name: '',
    model: '',
    modelType: '',
    embeddinglen:'',
    tokenslen:'',
    description: '',
    provider: provider,
    params: {},
    currentModel: null
  }
  
  modelDialogVisible.value = true
}

const editModel = (model: LLMModel) => {
  modelForm.value = {
    name: model.name,
    model: model.model,
    modelType: model.modelType,
    embeddinglen:'',
    tokenslen:'',
    description: model.description || '',
    provider: providers.value.find(p => p.urn === model.sp) || null,
    params: { ...model.config },
    currentModel: model
  }

  if (model.modelType == ModelType.EMBEDDING) {
    let dim = model.options['Dim']
    if (dim !== null && dim !== undefined) {
      modelForm.value.embeddinglen = dim
    }
  }
  
  if (model.modelType == ModelType.CHAT) {
    let maxTokens = model.options['MaxTokens']
    if (maxTokens !== null && maxTokens !== undefined) {
      modelForm.value.tokenslen = maxTokens
    }
  }
  modelDialogVisible.value = true
}

const deleteModel = async (model: LLMModel) => {
  try {
    const request = {
      urn: model.urn
    } as DeleteLLMModelRequest

    await DeleteModel(request)
    ElMessage.success('模型删除成功')
    
    // 找到对应的provider并重新加载其模型列表
    const provider = providers.value.find(p => p.urn === model.sp)
    if (provider) {
      loadModels(provider)
    }
  } catch (error) {
    ElMessage.error('删除失败：' + error)
  }
}

const getModelCount = (provider: LLMProvider): number => {
  if (providerModels.value === null) {
    return 0
  }
  const models = providerModels.value.get(provider.name)
  return models?.length||0
}

const getModels = (provider: LLMProvider): LLMModel[] => {
  if (providerModels.value === null) {
    return []
  }
  const models = providerModels.value.get(provider.name)
  return models||[]
}

const providerEditDialogVisible = ref(false)
const selectedEditSpec = ref<LLMProviderSpec | null>(null)
const providerEditForm = ref({
  name: '',
  endpoint: '',
  config: {} as Record<string, string>,
  authInfo: {} as Record<string, string>
})

const editProvider = (provider: LLMProvider) => {
  currentProvider.value = provider
  // Get the spec based on provider's provider field
  selectedEditSpec.value = providerSpecs.value.get(provider.provider) || null
  
  providerEditForm.value = {
    name: provider.name,
    endpoint: provider.accessUrl,
    config: {
      provider_name: provider.name,
      access_url: provider.accessUrl,
      provider_description: provider.description,
      api_name: provider.apiName
    },
    authInfo: { ...provider.authInfo }
  }
  providerEditDialogVisible.value = true
}

const saveProviderSettings = async () => {
  if (!currentProvider.value) return
  
  try {

    let p = { ...currentProvider.value } // Create a shallow copy
    const updateMask = []
    if (p.name !== providerEditForm.value.config["provider_name"]) {
      p.name = providerEditForm.value.config["provider_name"]
      updateMask.push("name")
    }

    if (p.accessUrl !== providerEditForm.value.config["access_url"]) {
      p.accessUrl = providerEditForm.value.config["access_url"]
      updateMask.push("access_url")
    }

    if (p.description !== providerEditForm.value.config["provider_description"]) {
      p.description = providerEditForm.value.config["provider_description"]
      updateMask.push("description")
    }

    console.log("providerEditForm.value.authInfo:",providerEditForm.value.authInfo)
    p.authInfo =providerEditForm.value.authInfo
    updateMask.push("auth_info")

    let request= {provider:p, updateMask:updateMask} as UpdateLLMProviderRequest


    await UpdateProvider(request)
    ElMessage.success('供应商设置已更新')
    providerEditDialogVisible.value = false
    loadProviders() // 重新加载供应商列表
  } catch (error) {
    ElMessage.error('更新失败：' + error)
  }
}

const loadModels = (provider:LLMProvider) => {
  const pageToken = { limit: pageSize, offset: 0 }
  let providerUrn = provider.urn
  const filter = `provider == '${providerUrn}'`
  ListModels({ pageSize: pageSize, pageToken, filter: filter }).then((res:ListLLMModelResponse)=>{
    providerModels.value.set(provider.name, res.models)
  }).catch(error => {
      console.error('Failed to fetch news:', error)
  })
}

const loadProviders = () => {
  const pageToken = { limit: pageSize, offset: 0 }
  const filter = ""
  ListProviders({ pageSize: pageSize, pageToken, filter: filter }).then((res:ListLLMProviderResponse)=>{
    totalProvider.value = res.totalSize
    providers.value=[]
    res.providers.forEach((provider) => {
      providers.value.push(provider)
      loadModels(provider)
    })
  }).catch(error => {
      console.error('Failed to fetch news:', error)
  })
}

const loadProviderSpecs = () => {
  let req = {} as ListLLMProviderSpecRequest
  ListProviderSpec(req).then((res:ListLLMProviderSpecResponse)=>{
    console.log("list spec res:",res)
    res.providers.forEach((spec) => {
      console.log("set value for", spec.name)
      providerSpecs.value.set(spec.name, spec)
    })
  }).catch(error => {
      console.error('Failed to fetch news:', error)
  })
}

const providerDialogVisible = ref(false)
const selectedSpec = ref<LLMProviderSpec | null>(null)
const providerForm = ref({
  specName: '',
  name: '',
  endpoint: '',
  authInfo: {} as Record<string, string>,
  config: {} as Record<string, string>
})

const openProviderDialog = () => {
  providerForm.value = {
    specName: '',
    name: '',
    endpoint: '',
    authInfo: {},
    config: {}
  }
  providerDialogVisible.value = true
}

const handleProviderSpecChange = (specName: string) => {
  selectedSpec.value = providerSpecs.value.get(specName) || null
  // Reset auth info when provider type changes
  providerForm.value.authInfo = {}
}

const saveProvider = async () => {
  try {
    let request = {
      name: providerForm.value.config["provider_name"],
      accessUrl: providerForm.value.config["access_url"],
      description:providerForm.value.config["provider_description"],
      apiName:providerForm.value.config["api_name"],
      authInfo: providerForm.value.authInfo,
      provider:providerForm.value.specName
    } as  CreateLLMProviderRequest
    
    await CreateProvider(request)
    ElMessage.success('供应商添加成功')
    providerDialogVisible.value = false
    loadProviders()
  } catch (error) {
    ElMessage.error('添加失败：' + error)
  }
}

// 修改响应式变量定义
const modelDialogVisible = ref(false)
const modelForm = ref({
  name: '',
  model: '',
  modelType: '',
  embeddinglen:'',
  tokenslen:'',
  description: '',
  provider: null as LLMProvider | null,
  params: {} as Record<string, string>,
  currentModel: null as LLMModel | null
})

// Add this watch statement after modelForm definition
watch(() => modelForm.value.model, (newValue) => {
  modelForm.value.name = newValue
})

// Modify saveModel to handle both create and edit
const saveModel = async () => {
  if (!modelForm.value.provider || !modelForm.value.name || !modelForm.value.model) {
    ElMessage.warning('请填写必要信息')
    return
  }

  let mt = ModelType[modelForm.value.modelType as keyof typeof ModelType] || ModelType.MODEL_TYPE_UNSPECIFIED

  try {
    

    if (modelForm.value.currentModel) {
      let m = {...modelForm.value.currentModel}
      let updateMask = []
      let curName = modelForm.value.provider.name + "/" + modelForm.value.name
      if (m.name != curName) {
        m.name = curName
        updateMask.push("name")
      }

      if (m.model != modelForm.value.model) {
        m.model = modelForm.value.model
        updateMask.push("model")
      }

      if (m.modelType != modelForm.value.modelType) {
        m.model = mt
        updateMask.push("type")
      }

      if ('' != modelForm.value.embeddinglen) {
        m.options = {}
        m.options["Dim"] = modelForm.value.embeddinglen
        updateMask.push("options")
      }

      if ('' != modelForm.value.tokenslen) {
        m.options = {}
        m.options["MaxTokens"] = modelForm.value.tokenslen
        updateMask.push("options")
      }
      // 更新已有模型
      const updateRequest = {
        model: m,
        updateMask: updateMask
      } as UpdateLLMModelRequest
      
      await UpdateModel(updateRequest)
      ElMessage.success('模型更新成功')
    } else {
        const baseRequest = {
        name:  modelForm.value.provider.name + "/" + modelForm.value.name,
        model: modelForm.value.model,
        modelType: mt,
        sp: modelForm.value.provider.urn,
        config: modelForm.value.params,
        options: {}
      } as CreateLLMModelRequest
      if (baseRequest.modelType === ModelType.EMBEDDING) {
        console.log("embeding len:", modelForm.value.embeddinglen)
        baseRequest.options["Dim"] = modelForm.value.embeddinglen
        console.log("embeding len2:", baseRequest.options["Dim"])
      }

      if (baseRequest.modelType === ModelType.CHAT) {
        console.log("tokens len:", modelForm.value.tokenslen)
        baseRequest.options["MaxTokens"] = modelForm.value.tokenslen
        console.log("tokens len2:", baseRequest.options["MaxTokens"])
      }
      // 创建新模型
      await CreateModel(baseRequest)
      ElMessage.success('模型添加成功')
    }

    modelDialogVisible.value = false
    
    if (modelForm.value.provider) {
      loadModels(modelForm.value.provider)
    }
  } catch (error) {
    ElMessage.error((modelForm.value.currentModel ? '更新' : '添加') + '失败：' + error)
  }
}

const deleteProvider = async (provider: LLMProvider) => {
  try {
    const request = {
      urn: provider.urn
    } as DeleteLLMProviderRequest

    await DeleteProvider(request)
    ElMessage.success('供应商删除成功')
    loadProviders() // 重新加载供应商列表
  } catch (error) {
    ElMessage.error('删除失败：' + error)
  }
}

onMounted(() => {
  // 可以在这里加载初始数据
  loadProviders()
  loadProviderSpecs()
})

// 添加 watch 来处理 specName 变化时的默认值设置
watch(() => providerForm.value.specName, (newSpecName) => {
  if (newSpecName) {
    const spec = providerSpecs.value.get(newSpecName)
    if (spec?.providerConfig) {
      spec.providerConfig.forEach(config => {
        if (config.defaultValue) {
          providerForm.value.config[config.variable] = config.defaultValue
        }
      })
    }
  }
})
</script>

<style scoped>
.llm-settings {
  padding: 24px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.model-cards {
  display: grid;
  gap: 20px;
}

.model-card {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}

.card-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  margin-bottom: 16px;
}

.provider-logo {
  width: 40px;
  height: 40px;
}

.provider-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  gap: 4px;
}

.provider-info h2 {
  margin: 0;
}

.provider-description {
  margin: 0;
  color: #666;
  font-size: 14px;
}

.capabilities {
  display: flex;
  gap: 8px;
  margin-bottom: 12px;
}

.tag {
  padding: 4px 8px;
  border-radius: 4px;
  background-color: #f5f5f5;
  margin-right: 8px;
  font-size: 12px;
  white-space: nowrap;
}

.api-section {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-top: 16px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background: #4CAF50;
}

.setup-btn, .show-models {
  padding: 8px 16px;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  background: white;
  cursor: pointer;
}

.models-section {
  margin-top: 16px;
}

.models-header {
  display: grid;
  grid-template-columns: 1fr auto 1fr;  /* 三列布局：左侧、中间、右侧 */
  align-items: center;
  padding: 0 8px;
}

.model-count {
  font-size: 14px;
  color: #666;
  text-align: left;
}

.center-container {
  grid-column: 2;  /* 放置在中间列 */
}

.show-models {
  padding: 8px 16px;
  border-radius: 4px;
  border: 1px solid #e0e0e0;
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
}

.show-models:hover {
  background: #f5f5f5;
}

.models-list {
  margin-top: 12px;
}

.model-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px;
  border: 1px solid #e0e0e0;
  border-radius: 4px;
  margin-bottom: 8px;
}

.model-actions {
  display: flex;
  align-items: center;
}

.more-actions {
  padding: 4px;
  background: transparent;
  border: none;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background-color 0.3s ease;
}

.more-actions:hover {
  background-color: #f5f5f5;
  border-radius: 4px;
}

.more-icon {
  width: 16px;
  height: 16px;
  object-fit: contain;
}

.menu-icon {
  width: 16px;
  height: 16px;
  margin-right: 8px;
  vertical-align: middle;
}

.el-dropdown-item {
  display: flex;
  align-items: center;
  padding: 8px 16px;
}

.add-model {
  width: 100%;
  padding: 8px;
  border: 1px dashed #e0e0e0;
  border-radius: 4px;
  background: transparent;
  cursor: pointer;
  margin-top: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
}

.add-model:hover {
  background-color: #f5f5f5;
}

.add-icon {
  width: 20px;
  height: 20px;
  object-fit: contain;
}

.status-dot.active {
  background: #4CAF50;
}

.status-dot:not(.active) {
  background: #ff5252;
}

.auth-item {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 8px;
}

.auth-item:last-child {
  margin-bottom: 0;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.edit-provider {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.04);
  border: none;
  padding: 6px;
  border-radius: 50%;
  cursor: pointer;
  transition: background-color 0.3s ease;
  margin-left: auto;  /* 确保按钮靠右 */
}

.edit-provider:hover {
  background-color: rgba(0, 0, 0, 0.08);
}

.setting-icon {
  width: 14px;
  height: 14px;
  object-fit: contain;
}

.expand-icon {
  width: 14px;
  height: 14px;
  object-fit: contain;
}

.model-count-section {
  display: flex;
  align-items: center;
  cursor: pointer;
  gap: 4px;
  padding: 4px;
  border-radius: 4px;
  transition: background-color 0.3s ease;
}

.settings-container {
  display: flex;
  justify-content: flex-end;  /* 右对齐 */
  margin: 8px 0;
}

.provider-settings {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.04);
  border: none;
  padding: 8px;  /* 调整为正方形的内边距 */
  border-radius: 50%;  /* 使按钮变成圆形 */
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.provider-settings:hover {
  background-color: rgba(0, 0, 0, 0.08);
}

.settings-icon {
  width: 16px;
  height: 16px;
  object-fit: contain;
}

.provider-actions {
  display: flex;
  gap: 8px;
  margin-left: auto;  /* 确保按钮靠右 */
}

.edit-provider,
.delete-provider {
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: rgba(0, 0, 0, 0.04);
  border: none;
  padding: 6px;
  border-radius: 50%;
  cursor: pointer;
  transition: background-color 0.3s ease;
}

.edit-provider:hover,
.delete-provider:hover {
  background-color: rgba(0, 0, 0, 0.08);
}

.delete-provider {
  background-color: rgba(255, 0, 0, 0.04);
}

.delete-provider:hover {
  background-color: rgba(255, 0, 0, 0.08);
}
</style>
